package ws

import (
	"errors"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/smash-llj/Nexa-server/utils"
)

type Handel struct {
	hub *Hub
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func NewHandel(hub *Hub) *Handel {
	return &Handel{
		hub: hub,
	}
}

func (h *Handel) Connect(c *gin.Context) {
	uid := int(utils.GetUserId(c))
	log.Printf("Connecting to %s", uid)
	if uid == 0 {
		c.JSON(http.StatusInternalServerError, gin.H{"error": errors.New("token解析失败")})
		return
	}
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	client := &Client{
		ID:      uid,
		Conn:    conn,
		Hub:     h.hub,
		Message: make(chan *Message),
	}

	h.hub.Register <- client

	go client.ReadMessage()
	go client.WriteMessage()
}
